package br.eng.eliseu.gwt.gestaoWeb.server.util;

import java.sql.Connection;
import java.sql.ResultSet;

import javax.naming.InitialContext;
import javax.sql.DataSource;

import com.google.inject.Provider;
import com.google.inject.Singleton;

@Singleton
public class ConnectionUtil implements Provider<Connection> {

	private static ConnectionUtil	connectionUtil;
	private DataSource				dataSource;
	private String					schemaName;

	public static ConnectionUtil getInstance() {
		if (connectionUtil == null) {
			connectionUtil = new ConnectionUtil();
		}

		return connectionUtil;
	}

	public Connection getConnection() throws Exception {
		DataSource ds = getDataSource();
		return ds.getConnection();
	}

	public String getSchemaName(Connection con) throws Exception {

		if (schemaName == null) {
			// Valido somente para oracle
			// Estudar multibanco quando necessario
			try {
				ResultSet rs = con.createStatement().executeQuery("select sys_context( 'userenv', 'current_schema' ) from dual");
				if (rs.next()) {
					schemaName = rs.getString(1);
				}
			} catch (Exception e) {
				throw new Exception("Não foi possível determinar o nome do schema", e);
			}
		}
		return schemaName;
	}

	// public String getSchemaName(Connection con) throws SonnerException {
	//
	// if (schemaName==null){
	// Document userBin = XMLUtil.getArquivoBin(null, "User.Bin");
	// NodeList conexoes = userBin.getElementsByTagName("conexao");
	// for (int i = 0; i < conexoes.getLength(); i++) {
	// Element conexao = (Element) conexoes.item(i);
	// if(conexao.hasAttribute("padraoCidadao")){
	// String padraoCidadao = conexao.getAttribute("padraoCidadao");
	// if("1".equals(padraoCidadao)){
	// //Encontramos a definicao da conexao web
	// schemaName = conexao.getAttribute("user");
	// }
	// }
	// }
	// }
	// return schemaName;
	// }

	private DataSource getDataSource() throws Exception {
		if (dataSource == null) {
			InitialContext ic = new InitialContext();
			dataSource = (DataSource) ic.lookup("java:comp/env/jdbc/gestaoWebDataSource");
		}
		return dataSource;
	}

	public Connection get() {
		try {
			return getConnection();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
}
